<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        :title="`${form.id ? '编辑' : '新增'}打卡方案`"
        :breadCrumb="breadCrumb"
        showBack
      ></pageHeaderNew>
    </template>
    <div class="wrap">
      <main>
        <a-form
          ref="formRef"
          :model="form"
          autoLabelWidth
          label-align="right"
          style="width: 50%; margin: 0 auto"
          :rules="rules"
        >
          <a-form-item field="name" label="打卡方案名称" required show-colon>
            <a-input v-model="form.name" />
          </a-form-item>
          <a-form-item label="打卡方式" required show-colon>
            <a-checkbox-group v-model="registrationMethod" direction="vertical">
              <a-checkbox :value="1">
                <template #checkbox="{ checked }">
                  <div style="display: flex; margin-bottom: 20px">
                    <a-space
                      align="start"
                      class="custom-checkbox-card"
                      :class="{ 'custom-checkbox-card-checked': checked }"
                    >
                      <div className="custom-checkbox-card-mask">
                        <div className="custom-checkbox-card-mask-dot" />
                      </div>
                      <div>
                        <div className="custom-checkbox-card-title">小程序</div>
                      </div>
                    </a-space>
                  </div>
                </template>
              </a-checkbox>
              <a-checkbox :value="2">
                <template #checkbox="{ checked }">
                  <div style="display: flex">
                    <a-space
                      align="start"
                      class="custom-checkbox-card"
                      :class="{ 'custom-checkbox-card-checked': checked }"
                    >
                      <div className="custom-checkbox-card-mask">
                        <div className="custom-checkbox-card-mask-dot" />
                      </div>
                      <div>
                        <div className="custom-checkbox-card-title">考勤机</div>
                      </div>
                    </a-space>
                  </div>
                </template>
              </a-checkbox>
            </a-checkbox-group>
            <div
              style="
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                margin-left: 20px;
                height: 90px;
              "
            >
              <div>
                <a-checkbox-group
                  :disabled="!registrationMethod.includes(1)"
                  direction="horizontal"
                  v-model="form.type"
                >
                  <a-checkbox :value="1">地点</a-checkbox>
                  <a-checkbox :value="2">WiFi</a-checkbox>
                  <a-checkbox :value="3">人脸识别</a-checkbox>
                </a-checkbox-group>
              </div>
              <a-space>
                <a-select
                  :disabled="!registrationMethod.includes(2)"
                  multiple
                  :style="{ width: '250px' }"
                  :options="machineList.data"
                  :max-tag-count="2"
                  :field-names="{ value: 'id', label: 'name' }"
                  v-model="form.machineIds"
                >
                </a-select>
                <a-space
                  style="color: #40a9ff; cursor: pointer"
                  @click="
                    router.push({
                      name: 'EditAttendanceMachine'
                    })
                  "
                >
                  <icon-plus />新增考勤机
                </a-space>
              </a-space>
            </div>
          </a-form-item>
        </a-form>
        <div v-show="registrationMethod.includes(1)">
          <!-- <header><h3>小程序</h3></header> -->
          <div v-show="form.type.includes(1)">
            <header>
              <h5 style="color: #40a9ff; font-size: 16px">地址</h5>
              <!-- <a-button type="primary" @click="MapShow = true">
                新增工作地址</a-button
              > -->
            </header>
            <mapModal
              ref="MapBox"
              @update="update"
              :data="form.attendanceClockInAddress"
            />
            <!-- <TableTurn :tableData="getTableData" ref="tableRef">
              <a-table-column :width="80">
                <template #title> 序号 </template>
                <template #cell="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="name"
                title="工作地址名称"
              >
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="name"
                title="地址范围"
              >
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="name"
                title="是否默认"
              >
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="name"
                title="操作"
              >
                <template #cell="{ record }">
                  <a-tooltip content="编辑">
                    <IconFont
                      type="icon-edit"
                      :size="26"
                      :style="{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }"
                      @click="edit(record)"
                    />
                  </a-tooltip>
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="del(record.id)"
                    >
                      <icon-font
                        type="icon-delete"
                        :size="26"
                        :style="{
                          cursor: 'pointer',
                          marginRight: '10px'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </template>
              </a-table-column>
            </TableTurn> -->
          </div>
          <div v-show="form.type.includes(2)">
            <header>
              <h5 style="color: #40a9ff; font-size: 16px">WiFi</h5>
              <a-button type="primary" @click="WiFiShow = true">
                新增打卡WiFi</a-button
              >
            </header>
            <TableTurn :tableData="getTableData" ref="wifiTableRef">
              <a-table-column :width="80">
                <template #title> 序号 </template>
                <template #cell="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="name"
                title="WIFI名称"
              >
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="bssid"
                title="BSSID地址"
              >
                <template #cell="{ record }">
                  {{ record.bssid?.join(':') }}</template
                >
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="ip"
                title="IP地址"
              >
                <template #cell="{ record }">
                  {{ record.ip?.join('.') }}</template
                >
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="mac"
                title="MAC地址"
              >
                <template #cell="{ record }">
                  {{ record.mac?.join(':') }}</template
                >
              </a-table-column>
              <a-table-column
                align="center"
                :width="200"
                data-index="name"
                title="操作"
              >
                <template #cell="{ record }">
                  <a-tooltip content="编辑">
                    <IconFont
                      type="icon-edit"
                      :size="26"
                      :style="{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }"
                      @click="
                        () => {
                          WiFiShow = true;
                          wifiData.data = record;
                        }
                      "
                    />
                  </a-tooltip>
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="delWifiData(record)"
                    >
                      <icon-font
                        type="icon-delete"
                        :size="26"
                        :style="{
                          cursor: 'pointer',
                          marginRight: '10px'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </template>
              </a-table-column>
            </TableTurn>
          </div>
        </div>
      </main>
      <footer>
        <a-button
          class="btn"
          style="
            margin-right: 20px;
            border: 1px rgba(242, 242, 242, 1) solid;
            background-color: #fff;
          "
          @click="$router.go(-1)"
          >返回</a-button
        >
        <a-button class="btn" type="primary" @click="save">保存</a-button>
      </footer>
    </div>
  </ContentCard>
  <wifiModal
    @upData="upWifiData"
    v-model:visible="WiFiShow"
    :data="wifiData.data"
  />
</template>
<script setup lang="ts">
import * as Type from './type';
import wifiModal from './wifiModal/index.vue';
import mapModal from './mapModal/index.vue';
import { Message } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import {
  PostAddressData,
  PutAddressData,
  RepeatAddressList
} from '@/apis/attendance/base-setting/index';
import { useRouter } from 'vue-router';
import { GetMachineList } from '@/apis/attendance/base-setting/index';
import TMap from './mapModal/type';

const router = useRouter();
const MapBox = ref<TMap>();

const breadCrumb: string[] = ['考勤', '基础设置', '打卡方式', '打卡方案'];
const wifiTableRef = ref();
const formRef = ref();
const registrationMethod = ref<(1 | 2)[]>([]);
const WiFiShow = ref(false);
const wifiData: { data: Type.Twifi | undefined } = reactive({
  data: undefined
});

const machineList: { data: Type.Twifi[] } = reactive({ data: [] });
const form = reactive<any>({
  name: '',
  type: [],
  machineIds: [],
  isSynchronization: 2,
  attendanceClockInWifi: [],
  attendanceClockInAddress: {}
});

watch(
  () => registrationMethod.value,
  (val) => {
    if (val.includes(2)) {
      if (!form.type.includes(4)) form.type.push(4);
    } else {
      form.type = form.type.filter((ele: number) => ele !== 4);
      form.machineIds = [];
    }
    if (!val.includes(1)) form.type = [];
    if (val.length === 0) {
      form.type = [];
    }
  }
);

const validateName = async (val: string, cb: any) => {
  try {
    if (form.id && form.name === val) {
      return;
    } else {
      const res = await RepeatAddressList({
        name: val
      });
      Message.error(`打卡方案名称${res.msg}`);
      if (res.code) cb(`打卡方案名称${res.msg}`);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
const rules = {
  name: [
    {
      required: true,
      message: '请填写名称',
      trigger: "['change', 'input', 'blur']"
    },
    {
      validator: validateName
    }
  ]
};

const del = (index: number) => {
  //
};

const update = (data: any) => {
  // form.attendanceClockInAddress = cloneDeep(data);
  Object.assign(form.attendanceClockInAddress, data);
};

onMounted(async () => {
  const data = JSON.parse(localStorage.getItem('machineManagement') + '');
  if (data) {
    if (data.machineIds.length !== 0) {
      registrationMethod.value.push(2);
    }
    if (data.type.length !== 0) {
      registrationMethod.value.push(1);
    }
    if (data.attendanceClockInWifi !== 0) {
      nextTick(() => {
        wifiTableRef.value.loadData();
      });
    }
  }
  Object.assign(form, data);

  const res = await GetMachineList({ pageNumber: -1, pageSize: 0 });
  machineList.data = res.content;
});
const upWifiData = (data: Type.Twifi) => {
  if (wifiData.data) {
    if (wifiData.data.id) {
      form.attendanceClockInWifi.forEach((ele: any) => {
        if (wifiData.data && ele.id === wifiData.data.id) {
          Object.assign(ele, data);
        }
      });
    } else {
      form.attendanceClockInWifi.forEach((ele: any) => {
        if (wifiData.data && ele.index === wifiData.data.index) {
          Object.assign(ele, data);
        }
      });
    }
  } else {
    form.attendanceClockInWifi.push(data);
  }
  wifiData.data = void 0;
  wifiTableRef.value.loadData();
};
const delWIFIids: number[] = [];
const delWifiData = (data: any) => {
  if (data.id) {
    delWIFIids.push(data.id);
  }
  form.attendanceClockInWifi.splice(
    form.attendanceClockInWifi.findIndex(
      (ele: any) => ele.index === data.index
    ),
    1
  );
  wifiTableRef.value.loadData();
};
const getTableData = async () => {
  form.attendanceClockInWifi.forEach(
    (ele: any, index: number) => (ele.index = index)
  );
  return form.attendanceClockInWifi;
};

const save = async () => {
  try {
    if (await formRef.value.validate()) return;
    MapBox.value?.upData();
    if (form.id) {
      if (delWIFIids.length !== 0) {
        //
        form.deleteWifiIds = delWIFIids;
      }
      await PutAddressData(form);
    } else {
      await PostAddressData(form);
    }
    router.back();
  } catch (error) {
    console.log(error);
  }
};
onUnmounted(() => {
  localStorage.removeItem('machineManagement');
});
</script>

<style lang="less" scoped>
.wrap {
  main {
    margin-bottom: 60px;
    overflow: hidden;

    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #f2f2f2;
      margin-bottom: 20px;
    }
    header h2 {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
    header h2::before {
      content: '';
      display: inline-block;
      width: 7px;
      height: 30px;
      background-color: #165dff;
      margin-right: 10px;
    }
  }
  footer {
    height: 60px;
    width: calc(100% - 100px);
    background-color: #fff;
    box-shadow: 1px -1px 10px 0 #cacaca;
    position: fixed;
    bottom: 0;
    left: 10%;
    display: flex;
    justify-content: center;
    align-items: center;

    .btn {
      width: 120px;
      height: 40px;
      border-radius: 5px;
    }
  }
}
.stepBox {
  width: 200px;
  text-align: start;

  div:nth-child(1) {
    font-size: 16px;
    margin-bottom: 5px;
  }
}
.step-two {
  width: 100%;
}
.prompt {
  display: flex;
  div:nth-child(2) {
    margin-left: 10px;
    p:nth-child(1) {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }
  }
}
.custom-checkbox-card {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  width: 100px;
  height: 50px;
  box-sizing: border-box;
}

.custom-checkbox-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  border: 1px solid var(--color-border-2);
  box-sizing: border-box;
}

.custom-checkbox-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}

.custom-checkbox-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: bold;
  // margin-bottom: 8px;
}

.custom-checkbox-card:hover,
.custom-checkbox-card-checked,
.custom-checkbox-card:hover .custom-checkbox-card-mask,
.custom-checkbox-card-checked .custom-checkbox-card-mask {
  border-color: rgb(var(--primary-6));
  display: flex;
  align-items: center;
}

.custom-checkbox-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-checkbox-card:hover .custom-checkbox-card-title,
.custom-checkbox-card-checked .custom-checkbox-card-title {
  color: rgb(var(--primary-6));
}

.custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
